import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/my_button.dart';
import 'package:nft_shop/widgets/my_scroll_view.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:url_launcher/url_launcher.dart';

class MyOrderDetailsPage extends StatefulWidget {
  OrderListModel model;

  MyOrderDetailsPage({Key? key, required this.model}) : super(key: key);

  @override
  _MyOrderDetailsPageState createState() => _MyOrderDetailsPageState();
}

class _MyOrderDetailsPageState extends State<MyOrderDetailsPage> {
  int endtime = 0;
  late TimerUtil _timerUtil;
  ConfigNameDetail? article;
  ConfigNameDetail? alArticle;
  StreamSubscription? testSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getConfigNameDetailAli("alipay_is_open");
    getConfigNameDetail("wechatpay_is_open");
    if (widget.model.status == 1) {
      endtime = widget.model.endTime!;
      _timerUtil = new TimerUtil(mTotalTime: endtime * 1000);
      _timerUtil.setOnTimerTickCallback((int tick) {
        setState(() {
          endtime -= 1;
        });
        if (endtime == 0) {
          _timerUtil.cancel();
          setState(() {});
        }
      });
      // //开始倒计时
      _timerUtil.startCountDown();
    }
  }

  @override
  void dispose() {
    super.dispose();
    try {
      _timerUtil.cancel();
      testSubscription?.cancel();
    } catch (e) {}
  }

  // Future<void> getData() async {
  //   await ServiceRepository.orderInfo(id: widget.id);
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "订单详情",
      ),
      body: MyScrollView(
        children: [
          widget.model.status != 1 ? topView2() : topView1(),
          widget.model.goodsOrderType == 1 ? goodsView1() : goodsView2(),
          Container(
            height: 5,
            color: Global.kTheme.colorLine,
          ),
          infoView(),
          widget.model.status == 1
              ? Container(
                  height: 40,
                  margin: EdgeInsets.only(
                    top: 25,
                    left: 14,
                    right: 14,
                  ),
                  decoration: BoxDecoration(
                    color: Global.kTheme.colorBackground3,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: MyButton(
                    minHeight: 50,
                    onPressed: () async {
                      int type = -1;
                      if (article?.value == "true" && alArticle?.value == "true") {
                        type = await showDialog(
                            context: context,
                            builder: (context) {
                              return new SimpleDialog(
                                title: Text("选择支付方式"),
                                children: [
                                  new SimpleDialogOption(
                                    child: payItem(
                                      icon: "icon_wx",
                                      title: "微信",
                                      describe: "选择微信支付",
                                    ),
                                    onPressed: () {
                                      Navigator.of(context).pop(2);
                                    },
                                  ),
                                  new SimpleDialogOption(
                                    child: payItem(
                                      icon: "icon_zfb",
                                      title: "支付宝",
                                      describe: "选择支付宝支付",
                                    ),
                                    onPressed: () {
                                      Navigator.of(context).pop(1);
                                    },
                                  ),
                                ],
                              );
                            });
                      } else {
                        if (article?.value == "true") {
                          type = 2;
                        } else if (alArticle?.value == "true") {
                          type = 1;
                        } else {
                          type = -1;
                        }
                      }
                      if ((alArticle?.value == "false" &&
                          article?.value == "false") || type == -1) {
                        EasyLoading.showToast("支付通道已关闭");
                        return;
                      }
                      EasyLoading.show(status: "加载中");
                      try {
                        if (type == 1) {
                          dynamic model;
                          model = await ServiceRepository.goodsPay3(
                              id: widget.model.id.toString());
                          // toAlipay(model);
                          toWebAipay(model);

                        } else {
                          dynamic wxData = await ServiceRepository.goodsWXPay(
                              id: widget.model.id.toString());
                          toWXPay(wxData);
                        }
                      } catch (e, s) {
                        EasyLoading.showToast(http.setError(e, s));
                      }
                    },
                    text: "立即支付",
                    fontSize: 16,
                    textColor: Colors.white,
                    backgroundColor: Global.kTheme.colorBackground3,
                  ),
                )
              : Container(),
          widget.model.status == 1
              ? Container(
                  height: 40,
                  margin: EdgeInsets.only(
                    top: 10,
                    left: 14,
                    right: 14,
                  ),
                  decoration: BoxDecoration(
                    color: Global.kTheme.colorBackground3,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: MyButton(
                    minHeight: 50,
                    onPressed: () async {
                      EasyLoading.show(status: "加载中");
                      try {
                        await ServiceRepository.cancelOrder(
                            widget.model.id.toString());
                        EasyLoading.showToast("取消成功");
                        Get.back();
                      } catch (e, s) {
                        EasyLoading.showToast(http.setError(e, s));
                      }
                    },
                    text: "取消订单",
                    fontSize: 16,
                    textColor: Global.kTheme.textPrimary4,
                    backgroundColor: Color(0xFFEFEFEF),
                  ),
                )
              : Container(),
        ],
      ),
    );
  }

  //头部
  Widget topView1() {
    return Container(
      height: 100,
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 25, vertical: 18),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF474747),
            Color(0xFF222222),
          ],
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "等待付款",
            style: TextStyle(
                fontSize: 20,
                color: Global.kTheme.textPrimary5,
                fontFamily: Global.mySemiboldFont),
          ),
          SizedBox(
            height: 8,
          ),
          Text(
            "请在 ${_durationTransform(endtime)}内付款",
            style: TextStyle(
              fontSize: 12,
              color: Global.kTheme.inputHint1,
            ),
          ),
        ],
      ),
    );
  }

  //头部
  Widget topView2() {
    String title = "";
    //1待付款 2(买)已完成 3代卖中 4(卖)已完成 5订单已超时 6已取消
    if (widget.model.status == 2) {
      title = "已完成";
    } else if (widget.model.status == 3) {
      title = "待卖中";
    } else if (widget.model.status == 4) {
      title = "已完成";
    } else if (widget.model.status == 5) {
      title = "已超时";
    } else if (widget.model.status == 6) {
      title = "已取消";
    }

    return Container(
      height: 100,
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 25, vertical: 18),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF474747),
            Color(0xFF222222),
          ],
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
                fontSize: 20,
                color: Global.kTheme.textPrimary5,
                fontFamily: Global.mySemiboldFont),
          ),
          SizedBox(
            height: 8,
          ),
          Text(
            "再逛逛,下一个会是有缘份的藏品哦~",
            style: TextStyle(
              fontSize: 12,
              color: Global.kTheme.inputHint1,
            ),
          ),
        ],
      ),
    );
  }

  //商品订单我的买单
  Widget goodsView1() {
    return Container(
      padding: EdgeInsets.only(left: 14, right: 10, top: 20, bottom: 15),
      child: Column(
        children: [
          Row(
            children: [
              LoadImage(
                widget.model.thumb ?? "",
                width: 80,
                height: 80,
              ),
              SizedBox(
                width: 13,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.model.goodsTitle ?? "",
                    style: TextStyle(
                        fontSize: 14, color: Global.kTheme.textPrimary4),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Text(
                    widget.model.nickname ?? "",
                    style: TextStyle(
                        fontSize: 14, color: Global.kTheme.inputHint1),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    "¥${widget.model.buyersPrice ?? ""}",
                    style: TextStyle(
                        fontSize: 13, color: Global.kTheme.textPrimary4),
                  ),
                ],
              )
            ],
          ),
          SizedBox(
            height: 10,
          ),
          Row(
            children: [
              Spacer(),
              Text(
                "支付金额",
                style: TextStyle(
                    fontSize: 13,
                    color: Global.kTheme.textPrimary4,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                width: 5,
              ),
              Text(
                "￥",
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0xFFDC241C),
                ),
              ),
              Text(
                "¥${widget.model.buyersPrice ?? ""}",
                style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFDC241C),
                    fontFamily: Global.myDINFont),
              ),
            ],
          )
        ],
      ),
    );
  }

  //商品订单我的卖单
  Widget goodsView2() {
    return Container(
      padding: EdgeInsets.only(left: 14, right: 10, top: 20, bottom: 15),
      child: Column(
        children: [
          Row(
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: LoadImage(
                    widget.model.thumb ?? "",
                    width: 80,
                    height: 80,
                  )),
              SizedBox(
                width: 13,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 1,
                  ),
                  Text(
                    widget.model.goodsTitle ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.textPrimary4,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  SizedBox(
                    height: 2,
                  ),
                  Text(
                    widget.model.nickname ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.inputHint1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  SizedBox(
                    height: 2,
                  ),
                  Text(
                    "买家ID:${widget.model.buyersMemberCode ?? ""}",
                    style: TextStyle(
                        fontSize: 12,
                        color: Global.kTheme.inputHint1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  SizedBox(
                    height: 2,
                  ),
                  SizedBox(
                    height: 2,
                  ),
                  Row(
                    children: [
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: "买入价格 ",
                          style: TextStyle(
                              fontSize: 12,
                              color: Global.kTheme.inputHint1,
                              fontFamily: Global.mySemiboldFont),
                        ),
                        TextSpan(
                          text: "¥${widget.model.buyersPrice ?? ""}",
                          style: TextStyle(
                              fontSize: 12,
                              color: Global.kTheme.textPrimary0,
                              fontFamily: Global.myDINFont),
                        ),
                      ])),
                      SizedBox(
                        width: 10,
                      ),
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: "卖出价格 ",
                          style: TextStyle(
                              fontSize: 12,
                              color: Global.kTheme.inputHint1,
                              fontFamily: Global.mySemiboldFont),
                        ),
                        TextSpan(
                          text: "¥${widget.model.sellerPrice ?? ""}",
                          style: TextStyle(
                              fontSize: 12,
                              color: Global.kTheme.textPrimary0,
                              fontFamily: Global.myDINFont),
                        ),
                      ])),
                    ],
                  )
                ],
              )
            ],
          ),
          SizedBox(
            height: 10,
          ),
          Row(
            children: [
              Spacer(),
              Text(
                "实付金额",
                style: TextStyle(
                    fontSize: 13,
                    color: Global.kTheme.textPrimary4,
                    fontFamily: Global.mySemiboldFont),
              ),
              SizedBox(
                width: 5,
              ),
              Text(
                "￥",
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0xFFDC241C),
                ),
              ),
              Text(
                "${widget.model.sellerPrice ?? ""}",
                style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFDC241C),
                    fontFamily: Global.myDINFont),
              ),
            ],
          )
        ],
      ),
    );
  }

  //订单信息
  Widget infoView() {
    List<Widget> data = [];
    //1待付款 2(买)已完成 3代卖中 4(卖)已完成 5订单已超时 6已取消
    if (widget.model.status == 1) {
      data.add(
        infoItem("订单编号", widget.model.ordersn ?? ""),
      );
      data.add(
        infoItem("下单时间", widget.model.placeTime ?? ""),
      );
    } else if (widget.model.status == 2) {
      data.add(
        infoItem("支付方式", "支付宝"),
      );
      data.add(
        infoItem("订单编号", widget.model.ordersn ?? ""),
      );
      data.add(
        infoItem("下单时间", widget.model.placeTime ?? ""),
      );
      data.add(
        infoItem("付款时间", widget.model.sellerTime ?? ""),
      );
    } else if (widget.model.status == 3) {
      data.add(
        infoItem("订单编号", widget.model.ordersn ?? ""),
      );
      data.add(
        infoItem("下单时间", widget.model.placeTime ?? ""),
      );
    } else if (widget.model.status == 4) {
      data.add(
        infoItem("支付方式", "支付宝"),
      );
      data.add(
        infoItem("订单编号", widget.model.ordersn ?? ""),
      );
      data.add(
        infoItem("下单时间", widget.model.placeTime ?? ""),
      );
      data.add(
        infoItem("付款时间", widget.model.sellerTime ?? ""),
      );
    } else if (widget.model.status == 5) {
      data.add(
        infoItem("订单编号", widget.model.ordersn ?? ""),
      );
      data.add(
        infoItem("下单时间", widget.model.placeTime ?? ""),
      );
    } else if (widget.model.status == 6) {
      data.add(
        infoItem("订单编号", widget.model.ordersn ?? ""),
      );
      data.add(
        infoItem("下单时间", widget.model.placeTime ?? ""),
      );
    }
    data.add(
      SizedBox(
        height: 10,
      ),
    );

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Column(children: data),
    );
  }

  Widget infoItem(String left, String right) {
    return Container(
      padding: EdgeInsets.only(top: 10),
      child: Row(
        children: [
          Text(
            left,
            style: TextStyle(fontSize: 12, color: Global.kTheme.inputHint1),
          ),
          Spacer(),
          Text(
            right,
            style: TextStyle(
                fontSize: 12,
                color: Global.kTheme.textPrimary4,
                fontFamily: Global.mySemiboldFont),
          )
        ],
      ),
    );
  }

  //时间转换 将秒转换为小时分钟
  String _durationTransform(int seconds) {
    var d = Duration(seconds: seconds);
    List<String> parts = d.toString().split(':');
    return '${parts[0]}小时${parts[1]}分${double.parse(parts[2]).truncate()}秒';
  }

  void toWebAipay(dynamic model) async{
    if(model["body"]!=null && model["body"]["pay_url"]!=null){
      var _url= model["body"]["pay_url"];
      if (!await launch(_url)) throw 'Could not launch $_url';
      EasyLoading.dismiss();

      await showDialog(
          context: context,
          builder: (context) {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.all(30),
              child: SizedBox(
                width: 200,
                height: 220,
                child: Container(
                  padding: EdgeInsets.all(30),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                      BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(Icons.offline_pin_rounded,size: 40,color: Colors.green,),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        "支付完成",
                        style: TextStyle(
                          fontSize: 18,
                          color: Global.kTheme.textPrimary6,
                          fontFamily: Global.mySemiboldFont,
                        ),
                      ),

                      SizedBox(
                        height: 10,
                      ),

                      SizedBox(
                        height: 10,
                      ),
                      MyButton(
                          minHeight: 40,
                          text: "完成",
                          fontSize: 17,
                          textColor: Global.kTheme.textPrimary5,
                          backgroundColor:
                          Global.kTheme.colorPrimary,
                          onPressed: () {
                            Navigator.of(Get.context!)
                              ..pop();
                            Get.back();
                          })
                    ],
                  ),
                ),
              ),
            );
          });
    }
  }
  //支付
  void toAlipay(SpecialCastModel model) async {
    print("支付中----");
    //检测是否安装支付宝
    var result = await tobias.isAliPayInstalled();

    if (!result) {
      return EasyLoading.showToast('请安装支付宝');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      var payResult = await tobias.aliPay(model.body ?? "");

      if (payResult['result'] != null) {
        if (payResult['resultStatus'].toString() == "9000") {
          EasyLoading.showToast('支付成功');
          Get.back();
        } else {
          EasyLoading.showToast('支付失败');
        }
      }
    }
  }

  void toWXPay(dynamic model) async {
    print("支付中----");
    await fluwx.registerWxApi(
        appId: "wx0f7153ca682343e0",
        universalLink: "https://www.com.example.limaiwl/app/");

    var result = await fluwx.isWeChatInstalled;
    if (!result) {
      return EasyLoading.showToast('请安装微信');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      // 将下面这些参数替换成后台返回的即可
      var payRes = await fluwx.payWithWeChat(
        appId: model["body"]["appid"],
        partnerId: model["body"]["partnerid"],
        prepayId: model["body"]["prepayid"],
        packageValue: model["body"]["package"],
        nonceStr: model["body"]["noncestr"],
        timeStamp: model["body"]["timestamp"],
        sign: model["body"]["sign"],
      );

      // 支付回调
      // 一般情况下打开微信支付闪退，errCode为 -1 ，多半是包名、签名和在微信开放平台创建时的配置不一致。
      // 监听支付结果
      if(testSubscription!=null){
        testSubscription?.cancel();
      }
      testSubscription = fluwx.weChatResponseEventHandler.listen((event) async {
        print(event.errCode);
        // 支付成功
        if (event.errCode == 0) {
          EasyLoading.showToast('支付成功');
          Get.back();
        } else {
          // 关闭弹窗
          EasyLoading.showToast('支付失败');
        }
      });
    }
  }

  void getConfigNameDetail(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          article = element;
        }
      });
    } catch (e, s) {}
    setState(() {});
  }
  void getConfigNameDetailAli(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          alArticle = element;
        }
      });
    } catch (e, s) {}
    setState(() {});
  }

  Widget payItem({
    String? icon,
    String? title,
    String? describe,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 14),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          LoadImage(
            icon!,
            width: 28,
            height: 28,
          ),
          SizedBox(
            width: 10,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title!,
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary6,
                    fontFamily: Global.mySemiboldFont),
              ),
              Text(
                describe!,
                style: TextStyle(fontSize: 12, color: Color(0xFFA0A0A0)),
              ),
            ],
          ),
          Spacer(),
          // Icon(
          //   (isSelect ?? false)
          //       ? Icons.check_circle
          //       : Icons.radio_button_unchecked_rounded,
          //   size: 18,
          // ),
        ],
      ),
    );
  }
}
